package com.xtm.exercise.base.A06Json;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xtm.exercise.base.B09copyBean.po.User;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.*;

/**
 * fastjson pom.xml
 *
 * @author wanglei
 */
// <dependency>
// <groupId>com.alibaba</groupId>
// <artifactId>fastjson</artifactId>
// <version>1.2.56</version>
// </dependency>
public class JsonTest {

	@Test
	public void test(){
		// JSON数组形式字符串转换为 List<T>
		String str = "[{'username':'zhansan' , 'age':'12' , 'sex':'男'},{'username':'lisi' , 'age':'19' , 'sex':'女'}]";
		List<User> response = JSONObject.parseObject(str, new TypeReference<List<User>>(){});
		System.out.println(response);
	}

	@Test
	public void StrToJson(){
		String jsonString = "{name:'Antony',age:'12',sex:'male'}";
		//json字符串转化为JSONObject对象
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		//从JSONObject 取值
		String name = jsonObject.getString("name");
		//从JSONObject 取空值
		String nullstr = jsonObject.getString("null");
		//向jsonObject1赋值
		jsonObject.put("address","天津");
		//对象转化为json字符串
		String json1 = JSON.toJSONString(jsonObject);

		//json字符串转化为PO对象
		User user = JSONObject.parseObject(jsonString, User.class);
		//对象转化为json字符串
		String jsonStr = JSON.toJSONString(user);
		//json字符串转化为Map对象
		Map map02 = JSONObject.parseObject(jsonString, Map.class);

		// JSON数组形式字符串转换为 List<T>
		String str = "[{'username':'zhansan' , 'age':'12' , 'sex':'男'},{'username':'lisi' , 'age':'19' , 'sex':'女'}]";
		List<User> users03 = JSONArray.parseArray(str, User.class);
		List<User> users = JSONObject.parseArray(str, User.class);
		List<User> list = JSONObject.parseObject(str, List.class);

		//多结构转换
		String jsonStringList = "{\"success\":true,\"data\":{\"pageSize\":200,\"pageNumber\":1,\"start\":0,\"end\":200,\"autoCount\":true,\"orderBy\":null,\"order\":null,\"expression\":null,\"params\":null,\"rows\":[{\"username\":\"李四\",\"age\":\"19\",\"sex\":\"男\"}],\"total\":1},\"message\":null}";
		JSONObject jsonObjectList1 = JSONObject.parseObject(jsonStringList);
		String data = jsonObjectList1.getString("data");
		Object row = JSONObject.parseObject(data).get("rows");
		List<User> list1 = JSONObject.parseArray(row.toString(), User.class);
//		List<CaseVo> casesList = JSON.parseArray(JSONObject.toJSONString(caseScheduleVoList), CaseVo.class);

		//重组扩展字段信息
		JSONObject object = new JSONObject();
		JSONObject json = JSONObject.parseObject(str);
		Iterator iter = json.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			if(!"age".equals(entry.getKey().toString())){
				object.put(entry.getKey().toString(),entry.getValue());
			}
		}
		String objectStr = JSONObject.toJSONString(object);
		System.out.println(objectStr);
	}

}
